package top.glike.funct.controller;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import top.glike.common.config.BedImgConfig;
import top.glike.common.core.domain.AjaxResult;
import top.glike.common.core.domain.model.LoginUser;
import top.glike.common.utils.SecurityUtils;
import top.glike.common.utils.file.FileUploadUtils;
import top.glike.common.utils.file.FileUtils;
import top.glike.funct.conf.ServerTempConfig;
import top.glike.funct.domain.BedFile;
import top.glike.funct.domain.BedToken;
import top.glike.funct.domain.BedType;
import top.glike.funct.domain.FileUpload;
import top.glike.funct.service.IBedFileService;
import top.glike.funct.service.IBedTokenService;
import top.glike.funct.service.IBedTypeService;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @PACKAGE_NAME: top.glike.controller
 * @CLASSNAME: TestController
 * @DEACRIPTION:
 * @AUTHOR: GuoChen
 * @DATE: 2024/3/6
 * @WEEK: 周三
 **/
@Slf4j
@RestController
@RequestMapping("/img")
public class BedImgController {

    @Autowired
    private ServerTempConfig serverConfig;
    @Autowired
    private IBedFileService bedFileService;
    @Autowired
    private IBedTypeService bedTypeService;
    @Autowired
    private IBedTokenService bedTokenService;
    @Autowired
    private BedImgConfig bedImgConfig;

    @PostMapping("/uploadPdfFile")
    public AjaxResult uploadPdfFile(FileUpload vo) {
        try {
            log.info("上传文件到服务器...");
            MultipartFile file = vo.getFile();
            Long typeId = 0l;
            String suffix = FilenameUtils.getExtension(file.getOriginalFilename());
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmss");
            Date date = new Date();
            String dateStr = sdf.format(date);
            String fileName = String.format("%s-%s.%s", suffix, dateStr, suffix);
            String uploadPath = BedImgConfig.getUploadPath();
            String filePath = uploadPath + "/" + typeId + "/" + fileName;
            log.info("上传的文件为：{}", filePath);
            File f = new File(filePath);
            FileCopyUtils.copy(file.getBytes(), f);
            // 获取当前登录人信息
            // Long userId = SecurityUtils.getLoginUser().getUserId();
            log.info("文件上传并记录成功！");


        } catch (Exception e) {
            log.error("文件上传出现异常: {}", e.getMessage());
            log.error(e.getMessage(), e);
            return AjaxResult.error("文件上传出现异常：{}", e.getMessage());
        }
        return AjaxResult.success();
    }

    /**
     * 单文件上传
     */
    @PostMapping("/upload")
    public AjaxResult uploadFile(FileUpload vo) {
        try {

            Long userId = -1l;
            try {
                LoginUser loginUser = SecurityUtils.getLoginUser();
                userId = loginUser.getUserId();
            } catch (Exception e) {
                log.info("获取用户登录信息出现异常：{}", e.getMessage());
                log.info("判断自定义token是否真实：{}", vo.getToken());
                BedToken bedToken = bedTokenService.selectBedTokenByToken(vo.getToken());
                if (bedToken == null) {
                    log.error("token不能为空!");
                    return AjaxResult.error("token不能为空!");
                }
                if (bedToken.getExpireTime().before(new Date())) {
                    log.error("token已过期！");
                    return AjaxResult.error("token已过期!");
                }
                userId = vo.getUserId();
            }

            MultipartFile file = vo.getFile();
            // 上传文件路径
            BedType bedType = bedTypeService.selectBedTypeByKey(vo.getTypeKey());
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.uploadCustom(bedType.getDirPath(), file, bedType.getDirName());
            // String url = serverConfig.getUrl() + fileName;
            String url = bedImgConfig.getProxyUrl() + fileName;
            AjaxResult ajax = AjaxResult.success();
            ajax.put("url", url);
            ajax.put("fileName", fileName);
            ajax.put("newFileName", FileUtils.getName(fileName));
            ajax.put("originalFilename", file.getOriginalFilename());
            BedFile bedFile = new BedFile();
            bedFile.setProxyFile(fileName);
            bedFile.setProxyUrl(bedImgConfig.getProxyUrl());
            bedFile.setTypeId(bedType.getId());
            bedFile.setFileName(FileUtils.getName(fileName));
            bedFile.setFilePath(bedType.getDirPath().replace("\\", "/") + fileName.replace("/profile/upload", ""));
            bedFile.setUrl(url);
            bedFile.setUserId(userId);
            bedFileService.insertBedFile(bedFile);
            return ajax;
        } catch (Exception e) {
            log.error("文件上传出现异常：{}", e.getMessage());
            log.error(e.getMessage(), e);
            return AjaxResult.error(e.getMessage());
        }
    }

}
